package xdu.lz.stage5_jucUtils.chapter5_lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created at 2019/10/19 0019 下午 8:40
 */
public class LockApi {

    /**
     * Lock接口的API
     *
     * 1、lock()  不能被打断
     * 2、lockInterruptibly()  允许被打断
     * 3、tryLock();尝试获取，立马返回，返回boolean
     * 4、tryLock(time,timeUnit);  最多等待time，也允许被打断
     * 5、unlock();
     * 6、Condition condition = lock.newCondition();
     */
    private static final Lock lock = new ReentrantLock();

    public static void lock(){
        try {
            //这个方法不可被中断
       //     lock.lock();
            //这个方法会被中断
            lock.lockInterruptibly();

            System.out.println(Thread.currentThread().getName()+" get the lock");
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
            System.out.println(Thread.currentThread().getName()+" release the lock");
        }
    }

    public static void main(String[] args) {

        for (int i = 0; i < 3 ; i++) {
            new Thread(()->{
                lock();
            },"t"+i).start();
        }
    }
}
